package Q5;

import java.io.*;

public class Util {
    public static void transfer(OutputStream out, InputStream in) throws IOException {
        int res = 0;
        byte[] bArr = new byte[1024];
        while((res = in.read(bArr))!=-1) {
            out.write(bArr);
        }
    }

    public static void filetoSocketMessageStream(ObjectOutputStream out, InputStream in, String content, String name)
            throws IOException {
        int res = 0;
        byte[] bArr = new byte[1024];
        while((res = in.read(bArr))!=-1) {
            out.writeObject(new Message("file", name, content, bArr, res));
        }

    }
    // socketMessage 向文件写入
    public static Message SocketMessagetoFile(ObjectInputStream in, Message Initial, String savePath) throws IOException, ClassNotFoundException {
        //起始的包
        File file = new File(savePath);
        if (!file.isDirectory()) {file.mkdir();}
        file = new File(file, Initial.getData());
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(Initial.getFileData(),0, Initial.getRes());
        //后续的包
        int res = 0;
        byte[] barr = new byte[1024];
        while(true) {
            // 读到最后返回
            Message msg = null;
            try {
                if (in.available() == 0) {
                    return null;
                }
                msg = (Message) in.readObject();
            } catch (EOFException e) {
                return null;
            } finally {
                fileOutputStream.close();
            }
            // 读到其他文件，返回新的开始的包
            if (!msg.getData().equals(Initial.getData())) {return msg;}
            fileOutputStream.write(msg.getFileData(),0, res);
        }
    }

}
